package com.atguigu.gulimall.search.service.impl;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import com.mysql.cj.x.protobuf.MysqlxNotice;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStatusUP(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest(); //   构建es请求对象
        for (SkuEsModel skuEsModel : skuEsModels) {  //  遍历 这些 sku
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX); //   创建索引对象
            indexRequest.id(skuEsModel.getSkuId().toString());//赋值
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON); // 赋值
            bulkRequest.add(indexRequest);  //  赋值
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS); //  上!!
        boolean b = bulk.hasFailures();
        BulkItemResponse[] items = bulk.getItems(); //  获取返回的结果
        Stream<BulkItemResponse> stream = Arrays.stream(items);
        List<String> collect = stream.map(item -> {
            String id = item.getId();
            return id;
        }).collect(Collectors.toList());  //  这是 出现问题 的  sku的id
        if(b){
        log.error("商品上架有错误!!{}",collect);
        }
        return b;
    }
}
